<template>
  <div class="booking-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-icon">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="header-content">
          <h1>台球桌预订</h1>
          <p>选择您喜欢的台球桌，享受精彩的台球时光</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button
          size="large"
          @click="$router.push('/orders')"
          class="action-btn secondary"
        >
          <el-icon><Document /></el-icon>
          我的订单
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="refreshTables"
          class="action-btn primary"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
      <div class="header-decoration">
        <div class="decoration-circle"></div>
        <div class="decoration-dots">
          <span v-for="i in 4" :key="i" class="dot"></span>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-card">
        <div class="filter-header">
          <div class="filter-title">
            <el-icon><Search /></el-icon>
            <span>筛选与搜索</span>
          </div>
          <div class="filter-actions">
            <el-button
              text
              @click="resetFilters"
              class="reset-btn"
            >
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>

        <div class="filter-content">
          <div class="filter-group">
            <label class="filter-label">台球桌类型</label>
            <el-select
              v-model="filters.tableType"
              placeholder="选择类型"
              clearable
              @change="handleFilterChange"
              class="filter-select"
            >
              <el-option label="全部类型" value="" />
              <el-option label="🎱 斯诺克" value="斯诺克" />
              <el-option label="🎯 美式台球" value="美式台球" />
              <el-option label="🔴 中式台球" value="中式台球" />
              <el-option label="🎯 九球" value="九球" />
            </el-select>
          </div>

          <div class="filter-group">
            <label class="filter-label">预订日期</label>
            <el-date-picker
              v-model="filters.date"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilterChange"
              class="filter-date"
            />
          </div>

          <div class="filter-group">
            <label class="filter-label">时间段</label>
            <el-select
              v-model="filters.timeSlot"
              placeholder="选择时间段"
              clearable
              @change="handleFilterChange"
              class="filter-select"
            >
              <el-option label="全部时段" value="" />
              <el-option label="🌅 上午 (09:00-12:00)" value="morning" />
              <el-option label="☀️ 下午 (12:00-18:00)" value="afternoon" />
              <el-option label="🌙 晚上 (18:00-23:00)" value="evening" />
            </el-select>
          </div>

          <div class="filter-group search-group">
            <label class="filter-label">快速操作</label>
            <div class="search-actions">
              <el-button
                type="primary"
                @click="searchTables"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </div>
          </div>
        </div>

        <!-- 当前筛选条件显示 -->
        <div v-if="hasActiveFilters" class="active-filters">
          <div class="filters-header">
            <span class="filters-title">当前筛选条件</span>
            <el-button text @click="resetFilters" class="clear-all-btn">
              清空全部
            </el-button>
          </div>
          <div class="filters-tags">
            <el-tag
              v-if="filters.tableType"
              closable
              @close="clearFilter('tableType')"
              class="filter-tag"
              type="primary"
            >
              类型：{{ getTypeText(filters.tableType) }}
            </el-tag>
            <el-tag
              v-if="filters.date"
              closable
              @close="clearFilter('date')"
              class="filter-tag"
              type="success"
            >
              日期：{{ filters.date }}
            </el-tag>
            <el-tag
              v-if="filters.timeSlot"
              closable
              @close="clearFilter('timeSlot')"
              class="filter-tag"
              type="warning"
            >
              时间段：{{ getTimeSlotText(filters.timeSlot) }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 台球桌列表 -->
    <div class="tables-section">
      <div class="section-header">
        <div class="section-title">
          <h3>可预订台球桌</h3>
          <span class="table-count">共 {{ filteredTables.length }} 张台球桌</span>
        </div>
        <div class="view-options">
          <el-button-group>
            <el-button
              :type="viewMode === 'grid' ? 'primary' : ''"
              @click="viewMode = 'grid'"
              size="small"
            >
              <el-icon><Grid /></el-icon>
              网格
            </el-button>
            <el-button
              :type="viewMode === 'list' ? 'primary' : ''"
              @click="viewMode = 'list'"
              size="small"
            >
              <el-icon><List /></el-icon>
              列表
            </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="tables-grid" :class="{ 'list-view': viewMode === 'list' }">
        <div
          v-for="table in filteredTables"
          :key="table.id"
          class="table-card"
          :class="[`status-${table.status}`]"
          @click="openBookingDialog(table)"
        >
          <div class="table-header">
            <div class="table-type-icon">
              {{ getTypeIcon(table.type) }}
            </div>
            <div class="table-status-indicator">
              <div :class="['status-dot', table.status]"></div>
            </div>
          </div>

          <div class="table-content">
            <div class="table-title">
              <h3>{{ getTypeText(table.type) }}</h3>
              <span class="table-name">{{ table.name }}</span>
            </div>

            <div class="table-status">
              <span :class="['status-text', table.status]">
                {{ getStatusText(table.status) }}
              </span>
            </div>

            <div class="table-price">
              <span class="price-amount">¥{{ table.hourlyRate }}</span>
              <span class="price-unit">/小时</span>
            </div>

            <div class="table-description">
              <p>{{ table.description }}</p>
            </div>
          </div>

          <div class="table-actions">
            <el-button
              :type="table.status === 'available' ? 'primary' : 'warning'"
              size="large"
              :disabled="table.status === 'maintenance'"
              @click.stop="openBookingDialog(table)"
              class="booking-btn"
            >
              <el-icon v-if="table.status === 'available'"><VideoPlay /></el-icon>
              <el-icon v-else-if="table.status === 'occupied'"><Clock /></el-icon>
              <el-icon v-else><Tools /></el-icon>
              {{ getBookingButtonText(table.status) }}
            </el-button>
          </div>

          <div class="table-decoration">
            <div class="decoration-pattern"></div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredTables.length === 0" class="empty-state">
        <el-empty description="暂无符合条件的台球桌">
          <el-button type="primary" @click="resetFilters">
            重置筛选条件
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 预订对话框 -->
    <el-dialog
      v-model="bookingDialogVisible"
      title="预订台球桌"
      width="1200px"
      :before-close="handleCloseDialog"
    >
      <el-form :model="bookingForm" :rules="bookingRules" ref="bookingFormRef" label-width="100px">
        <el-form-item label="台球桌" prop="tableName">
          <el-input v-model="bookingForm.tableName" disabled></el-input>
        </el-form-item>
        <el-form-item label="预订日期" prop="date">
          <el-date-picker
            v-model="bookingForm.date"
            type="date"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="时间段" prop="timeSlots">
          <div class="time-slots-container">
            <div class="time-slots-grid">
              <div
                v-for="slot in availableTimeSlots"
                :key="slot.value"
                class="time-slot-item"
                :class="{
                  'selected': bookingForm.timeSlots.includes(slot.value),
                  'disabled': slot.disabled || slot.isPast,
                  'booked': slot.isBooked,
                  'past': slot.isPast
                }"
                @click="toggleTimeSlot(slot)"
              >
                <div class="slot-time">{{ slot.label }}</div>
                <div class="slot-status">
                  <span v-if="slot.isPast" class="status-text past">已过期</span>
                  <span v-else-if="slot.isBooked" class="status-text booked">已预订</span>
                  <span v-else-if="bookingForm.timeSlots.includes(slot.value)" class="status-text selected">已选择</span>
                  <span v-else class="status-text available">可选择</span>
                </div>
              </div>
            </div>
            <div class="selected-summary" v-if="bookingForm.timeSlots.length > 0">
              <p><strong>已选择时间段：</strong></p>
              <div class="selected-slots">
                <el-tag
                  v-for="slotValue in bookingForm.timeSlots"
                  :key="slotValue"
                  type="primary"
                  closable
                  @close="removeTimeSlot(slotValue)"
                >
                  {{ getSlotLabel(slotValue) }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="bookingForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="bookingForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          ></el-input>
        </el-form-item>
        <el-form-item label="预计费用">
          <div class="cost-info">
            <span class="cost-text">{{ calculateCost() }}元</span>
            <span class="cost-detail">（{{ getDuration() }}小时 × {{ selectedTable?.hourlyRate || 0 }}元/小时）</span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBooking" :loading="submitting">确认预订</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useUserStore } from '../store/modules/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createOrder, getBookedSlots } from '../api/order';
import { getTables } from '../api/table';
import {
  Calendar,
  Document,
  Refresh,
  Search,
  Grid,
  List,
  VideoPlay,
  Clock,
  Tools
} from '@element-plus/icons-vue';

export default {
  name: 'Booking',
  components: {
    Calendar,
    Document,
    Refresh,
    Search,
    Grid,
    List,
    VideoPlay,
    Clock,
    Tools
  },
  setup() {
    const userStore = useUserStore();
    const bookingFormRef = ref();
    const bookingDialogVisible = ref(false);
    const submitting = ref(false);
    const selectedTable = ref(null);
    const viewMode = ref('grid'); // 'grid' 或 'list'

    // 筛选条件
    const filters = reactive({
      tableType: '',
      date: '',
      timeSlot: ''
    });

    // 预订表单
    const bookingForm = reactive({
      tableId: '',
      tableName: '',
      date: '',
      timeSlots: [],
      startTime: '',
      endTime: '',
      phone: '',
      remark: ''
    });

    // 表单验证规则
    const bookingRules = {
      date: [
        { required: true, message: '请选择预订日期', trigger: 'change' }
      ],
      timeSlots: [
        {
          validator: (rule, value, callback) => {
            if (!value || value.length === 0) {
              callback(new Error('请至少选择一个时间段'));
            } else {
              callback();
            }
          },
          trigger: 'change'
        }
      ],
      phone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
          pattern: /^1[3-9]\d{9}$/,
          message: '请输入正确的手机号码（11位数字，以1开头）',
          trigger: 'blur'
        }
      ]
    };

    // 台球桌数据
    const tables = ref([]);
    const loading = ref(false);

    // 固定时间段定义（1小时为单位）
    const timeSlots = [
      { value: 'slot_09', label: '09:00-10:00', startTime: '09:00', endTime: '10:00', duration: 1, hour: 9 },
      { value: 'slot_10', label: '10:00-11:00', startTime: '10:00', endTime: '11:00', duration: 1, hour: 10 },
      { value: 'slot_11', label: '11:00-12:00', startTime: '11:00', endTime: '12:00', duration: 1, hour: 11 },
      { value: 'slot_12', label: '12:00-13:00', startTime: '12:00', endTime: '13:00', duration: 1, hour: 12 },
      { value: 'slot_13', label: '13:00-14:00', startTime: '13:00', endTime: '14:00', duration: 1, hour: 13 },
      { value: 'slot_14', label: '14:00-15:00', startTime: '14:00', endTime: '15:00', duration: 1, hour: 14 },
      { value: 'slot_15', label: '15:00-16:00', startTime: '15:00', endTime: '16:00', duration: 1, hour: 15 },
      { value: 'slot_16', label: '16:00-17:00', startTime: '16:00', endTime: '17:00', duration: 1, hour: 16 },
      { value: 'slot_17', label: '17:00-18:00', startTime: '17:00', endTime: '18:00', duration: 1, hour: 17 },
      { value: 'slot_18', label: '18:00-19:00', startTime: '18:00', endTime: '19:00', duration: 1, hour: 18 },
      { value: 'slot_19', label: '19:00-20:00', startTime: '19:00', endTime: '20:00', duration: 1, hour: 19 },
      { value: 'slot_20', label: '20:00-21:00', startTime: '20:00', endTime: '21:00', duration: 1, hour: 20 },
      { value: 'slot_21', label: '21:00-22:00', startTime: '21:00', endTime: '22:00', duration: 1, hour: 21 },
      { value: 'slot_22', label: '22:00-23:00', startTime: '22:00', endTime: '23:00', duration: 1, hour: 22 }
    ];

    // 已预订的时间段
    const bookedSlots = ref([]);

    // 获取台球桌列表
    const fetchTables = async () => {
      try {
        loading.value = true;
        const response = await getTables();
        if (response.success) {
          // 处理后端返回的数据格式：{success: true, data: {items: [...], total: 8}}
          const tablesData = response.data.items || response.data.tables || response.data;
          tables.value = tablesData.map(table => ({
            id: table.id,
            name: table.name,
            type: table.type,
            status: table.status,
            hourlyRate: table.hourly_rate,
            description: table.description || `${table.type}，设备齐全`
          }));
        } else {
          ElMessage.error(response.message || '获取台球桌列表失败');
        }
      } catch (error) {
        console.error('获取台球桌列表失败:', error);
        ElMessage.error('获取台球桌列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 过滤后的台球桌
    const filteredTables = computed(() => {
      return tables.value.filter(table => {
        if (filters.tableType && table.type !== filters.tableType) {
          return false;
        }
        // 这里可以添加更多筛选逻辑，比如根据时间段筛选
        return true;
      });
    });

    // 是否有激活的筛选条件
    const hasActiveFilters = computed(() => {
      return filters.tableType || filters.date || filters.timeSlot;
    });

    // 可用时间段（排除已预订的和过去的时间）
    const availableTimeSlots = computed(() => {
      if (!selectedTable.value || !bookingForm.date) {
        return timeSlots.map(slot => ({ ...slot, disabled: false, isBooked: false, isPast: false }));
      }

      const now = new Date();
      const selectedDate = new Date(bookingForm.date);
      const isToday = selectedDate.toDateString() === now.toDateString();

      return timeSlots.map(slot => {
        // 检查是否已预订
        const isBooked = bookedSlots.value.some(booked =>
          (booked.time_slot && booked.time_slot === slot.value) ||
          (
            booked.start_time && booked.end_time &&
            (slot.startTime + ':00' === booked.start_time && slot.endTime + ':00' === booked.end_time)
          )
        );

        // 检查是否是过去的时间
        let isPast = false;
        if (isToday) {
          const currentHour = now.getHours();
          isPast = slot.hour <= currentHour;
        }

        const disabled = isBooked || isPast;

        return {
          ...slot,
          disabled,
          isBooked,
          isPast
        };
      });
    });

    // 禁用过去的日期
    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7; // 禁用昨天及之前的日期
    };

    // 禁用的小时
    const disabledHours = () => {
      const hours = [];
      for (let i = 0; i < 9; i++) {
        hours.push(i); // 禁用0-8点
      }
      for (let i = 23; i < 24; i++) {
        hours.push(i); // 禁用23点之后
      }
      return hours;
    };

    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        available: 'success',
        occupied: 'danger',
        maintenance: 'warning'
      };
      return statusMap[status] || 'info';
    };

    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        available: '可预订',
        occupied: '使用中',
        maintenance: '维护中'
      };
      return statusMap[status] || '未知';
    };

    // 获取预订按钮文本
    const getBookingButtonText = (status) => {
      const buttonTextMap = {
        available: '立即预订',
        occupied: '预订时段',
        maintenance: '暂不可用'
      };
      return buttonTextMap[status] || '立即预订';
    };

    // 获取时间段文本
    const getTimeSlotText = (timeSlot) => {
      const timeSlotMap = {
        morning: '上午 (09:00-12:00)',
        afternoon: '下午 (12:00-18:00)',
        evening: '晚上 (18:00-23:00)'
      };
      return timeSlotMap[timeSlot] || timeSlot;
    };

    // 获取台球桌类型文本
    const getTypeText = (type) => {
      // 直接返回类型，因为后端已经返回中文
      return type;
    };

    // 获取台球桌类型图标
    const getTypeIcon = (type) => {
      const iconMap = {
        '斯诺克': '🎱',
        '美式台球': '🎯',
        '中式台球': '🔴',
        '九球': '🎯'
      };
      return iconMap[type] || '🎱';
    };

    // 刷新台球桌数据
    const refreshTables = async () => {
      await fetchTables();
      ElMessage.success('数据刷新成功');
    };

    // 筛选条件变化处理
    const handleFilterChange = () => {
      // 实时更新筛选结果
      ElMessage.success('筛选条件已更新');
    };

    // 清除单个筛选条件
    const clearFilter = (filterKey) => {
      filters[filterKey] = '';
      handleFilterChange();
    };

    // 重置所有筛选条件
    const resetFilters = () => {
      filters.tableType = '';
      filters.date = new Date().toISOString().split('T')[0]; // 保持今天的日期
      filters.timeSlot = '';
      ElMessage.success('筛选条件已重置');
    };

    // 搜索台球桌
    const searchTables = () => {
      // 这里可以添加更复杂的搜索逻辑
      ElMessage.success('搜索完成');
    };

    // 切换时间段选择
    const toggleTimeSlot = (slot) => {
      if (slot.disabled || slot.isPast || slot.isBooked) {
        return;
      }

      const index = bookingForm.timeSlots.indexOf(slot.value);
      if (index > -1) {
        // 如果已选择，则取消选择
        bookingForm.timeSlots.splice(index, 1);
      } else {
        // 如果未选择，则添加选择
        bookingForm.timeSlots.push(slot.value);
      }

      // 更新开始和结束时间
      updateTimeRange();
    };

    // 移除时间段
    const removeTimeSlot = (slotValue) => {
      const index = bookingForm.timeSlots.indexOf(slotValue);
      if (index > -1) {
        bookingForm.timeSlots.splice(index, 1);
        updateTimeRange();
      }
    };

    // 获取时间段标签
    const getSlotLabel = (slotValue) => {
      const slot = timeSlots.find(s => s.value === slotValue);
      return slot ? slot.label : slotValue;
    };

    // 更新时间范围
    const updateTimeRange = () => {
      if (bookingForm.timeSlots.length === 0) {
        bookingForm.startTime = '';
        bookingForm.endTime = '';
        return;
      }

      // 排序选中的时间段
      const sortedSlots = bookingForm.timeSlots
        .map(value => timeSlots.find(slot => slot.value === value))
        .filter(slot => slot)
        .sort((a, b) => a.hour - b.hour);

      if (sortedSlots.length > 0) {
        bookingForm.startTime = sortedSlots[0].startTime;
        bookingForm.endTime = sortedSlots[sortedSlots.length - 1].endTime;
      }
    };

    // 获取已预订的时间段
    const fetchBookedSlots = async (tableId, date) => {
      try {
        const response = await getBookedSlots(tableId, date);
        if (response.success) {
          bookedSlots.value = response.data;
        } else {
          bookedSlots.value = [];
        }
      } catch (error) {
        console.error('获取已预订时间段失败:', error);
        bookedSlots.value = [];
      }
    };

    // 打开预订对话框
    const openBookingDialog = async (table) => {
      selectedTable.value = table;
      bookingForm.tableId = table.id;
      bookingForm.tableName = table.name;
      bookingForm.phone = userStore.userInfo.phone || '';
      bookingForm.date = filters.date || new Date().toISOString().split('T')[0];

      // 获取已预订的时间段
      await fetchBookedSlots(table.id, bookingForm.date);

      bookingDialogVisible.value = true;
    };

    // 关闭对话框
    const handleCloseDialog = (done) => {
      ElMessageBox.confirm('确认关闭预订对话框？')
        .then(() => {
          resetBookingForm();
          done();
        })
        .catch(() => {});
    };

    // 重置预订表单
    const resetBookingForm = () => {
      Object.assign(bookingForm, {
        tableId: '',
        tableName: '',
        date: '',
        timeSlots: [],
        startTime: '',
        endTime: '',
        phone: '',
        remark: ''
      });
      selectedTable.value = null;
      bookedSlots.value = [];
    };

    // 计算时长
    const getDuration = () => {
      return bookingForm.timeSlots.length; // 每个时间段1小时
    };

    // 计算费用
    const calculateCost = () => {
      const duration = getDuration();
      const rate = selectedTable.value?.hourlyRate || 0;
      return Math.round(duration * rate);
    };

    // 提交预订
    const submitBooking = async () => {
      try {
        await bookingFormRef.value.validate();

        if (bookingForm.timeSlots.length === 0) {
          ElMessage.error('请选择时间段');
          return;
        }

        if (getDuration() <= 0) {
          ElMessage.error('无效的时间段');
          return;
        }

        submitting.value = true;

        // 为每个选中的时间段创建订单
        const orders = [];
        for (const timeSlotValue of bookingForm.timeSlots) {
          const slot = timeSlots.find(s => s.value === timeSlotValue);
          if (slot) {
            const orderData = {
              table_id: parseInt(bookingForm.tableId),
              booking_date: bookingForm.date,
              start_time: slot.startTime + ':00', // 添加秒数
              end_time: slot.endTime + ':00',     // 添加秒数
              phone: bookingForm.phone,
              remark: bookingForm.remark || ''
            };
            orders.push(orderData);
          }
        }

        // 保存到数据库
        try {
          for (const orderData of orders) {
            const response = await createOrder(orderData);
            if (!response.success) {
              throw new Error(response.message || '创建订单失败');
            }
          }
        } catch (error) {
          console.error('创建订单失败:', error);
          ElMessage.error('预订失败，请稍后重试');
          return;
        }

        ElMessage.success(`预订成功！共预订了${bookingForm.timeSlots.length}个时间段`);
        bookingDialogVisible.value = false;
        resetBookingForm();

        // 刷新台球桌列表以更新状态
        await fetchTables();

      } catch (error) {
        console.error('预订失败:', error);
      } finally {
        submitting.value = false;
      }
    };

    // 监听预订日期变化，重新获取已预订时段
    watch(() => bookingForm.date, async (newDate) => {
      if (newDate && selectedTable.value) {
        await fetchBookedSlots(selectedTable.value.id, newDate);
      }
    });

    onMounted(() => {
      // 设置默认日期为今天
      filters.date = new Date().toISOString().split('T')[0];
      // 获取台球桌列表
      fetchTables();
    });

    return {
      filters,
      tables,
      filteredTables,
      hasActiveFilters,
      loading,
      viewMode,
      bookingDialogVisible,
      bookingForm,
      bookingRules,
      bookingFormRef,
      submitting,
      selectedTable,
      timeSlots,
      bookedSlots,
      availableTimeSlots,
      disabledDate,
      disabledHours,
      getStatusType,
      getStatusText,
      getBookingButtonText,
      getTimeSlotText,
      getTypeText,
      getTypeIcon,
      refreshTables,
      handleFilterChange,
      toggleTimeSlot,
      removeTimeSlot,
      getSlotLabel,
      clearFilter,
      resetFilters,
      searchTables,
      fetchTables,
      fetchBookedSlots,
      openBookingDialog,
      handleCloseDialog,
      resetBookingForm,
      getDuration,
      calculateCost,
      submitBooking
    };
  }
};
</script>

<style scoped>
.booking-container {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  color: white;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transform: translate(50%, -50%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
  z-index: 1;
}

.header-icon {
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  backdrop-filter: blur(10px);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 16px;
  z-index: 1;
}

.action-btn {
  border: none !important;
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px);
}

.action-btn.primary {
  background: rgba(255, 255, 255, 0.2) !important;
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
}

.action-btn.primary:hover {
  background: rgba(255, 255, 255, 0.3) !important;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 255, 255, 0.3);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: translateY(-2px);
}

.header-decoration {
  position: absolute;
  top: 50%;
  right: 80px;
  transform: translateY(-50%);
  z-index: 1;
}

.decoration-circle {
  width: 150px;
  height: 150px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  position: relative;
}

.decoration-dots {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.decoration-dots .dot {
  width: 6px;
  height: 6px;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 50%;
  animation: float 3s ease-in-out infinite;
}

.decoration-dots .dot:nth-child(2) {
  animation-delay: 0.5s;
}

.decoration-dots .dot:nth-child(3) {
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% { transform: translateY(0); opacity: 0.4; }
  50% { transform: translateY(-8px); opacity: 1; }
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 32px;
}

.filter-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.filter-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.filter-title .el-icon {
  color: #667eea;
}

.reset-btn {
  color: #64748b !important;
  font-size: 14px !important;
}

.reset-btn:hover {
  color: #667eea !important;
}

.filter-content {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  gap: 24px;
  align-items: end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.filter-select,
.filter-date {
  width: 100%;
}

.search-group {
  position: relative;
}

.search-actions {
  display: flex;
  gap: 12px;
}

.search-btn {
  width: 100%;
  border-radius: 12px !important;
  font-weight: 600 !important;
}

/* 当前筛选条件显示 */
.active-filters {
  margin-top: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #f0f4ff 0%, #e0f2fe 100%);
  border-radius: 16px;
  border: 2px solid rgba(102, 126, 234, 0.2);
}

.filters-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.filters-title {
  font-size: 16px;
  font-weight: 600;
  color: #667eea;
}

.clear-all-btn {
  color: #64748b !important;
  font-size: 14px !important;
}

.clear-all-btn:hover {
  color: #ef4444 !important;
}

.filters-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-tag {
  border-radius: 8px !important;
  font-weight: 500 !important;
  padding: 6px 12px !important;
}

/* 台球桌区域 */
.tables-section {
  margin-bottom: 48px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
}

.table-count {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.view-options .el-button-group .el-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

.tables-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.tables-grid.list-view {
  grid-template-columns: 1fr;
}

.tables-grid.list-view .table-card {
  display: flex;
  align-items: center;
  padding: 20px 24px;
}

.tables-grid.list-view .table-content {
  display: flex;
  align-items: center;
  gap: 24px;
  flex: 1;
}

.table-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 2px solid #e2e8f0;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.table-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.15);
  border-color: #667eea;
}

.table-card.status-available {
  border-left: 6px solid #10b981;
  background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
}

.table-card.status-occupied {
  border-left: 6px solid #f59e0b;
  background: linear-gradient(135deg, #ffffff 0%, #fef3f2 100%);
}

.table-card.status-maintenance {
  border-left: 6px solid #ef4444;
  background: linear-gradient(135deg, #ffffff 0%, #fef2f2 100%);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-type-icon {
  font-size: 32px;
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #f8fafc, #e2e8f0);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid #e2e8f0;
}

.table-status-indicator {
  position: relative;
}

.status-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  position: relative;
}

.status-dot.available {
  background: #10b981;
  box-shadow: 0 0 0 4px rgba(16, 185, 129, 0.2);
}

.status-dot.occupied {
  background: #f59e0b;
  box-shadow: 0 0 0 4px rgba(245, 158, 11, 0.2);
}

.status-dot.maintenance {
  background: #ef4444;
  box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.2);
}

.status-dot::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 8px;
  height: 8px;
  background: white;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

.table-content {
  margin-bottom: 24px;
}

.table-title {
  margin-bottom: 16px;
}

.table-title h3 {
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
  margin: 0 0 4px 0;
}

.table-name {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  background: #f1f5f9;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-block;
}

.table-status {
  margin-bottom: 16px;
}

.status-text {
  font-size: 14px;
  font-weight: 600;
  padding: 6px 12px;
  border-radius: 8px;
  display: inline-block;
}

.status-text.available {
  background: rgba(16, 185, 129, 0.1);
  color: #059669;
}

.status-text.occupied {
  background: rgba(245, 158, 11, 0.1);
  color: #d97706;
}

.status-text.maintenance {
  background: rgba(239, 68, 68, 0.1);
  color: #dc2626;
}

.table-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
  margin-bottom: 16px;
}

.price-amount {
  font-size: 24px;
  font-weight: 700;
  color: #059669;
}

.price-unit {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.table-description {
  margin-bottom: 20px;
}

.table-description p {
  font-size: 14px;
  color: #64748b;
  line-height: 1.5;
  margin: 0;
}

.table-actions {
  display: flex;
  justify-content: center;
}

.booking-btn {
  padding: 12px 24px !important;
  font-size: 16px !important;
  font-weight: 600 !important;
  border-radius: 12px !important;
  transition: all 0.3s ease !important;
  width: 100%;
}

.booking-btn:hover {
  transform: translateY(-2px) !important;
}

.table-decoration {
  position: absolute;
  top: -20px;
  right: -20px;
  width: 80px;
  height: 80px;
  opacity: 0.05;
  pointer-events: none;
}

.decoration-pattern {
  width: 100%;
  height: 100%;
  background: radial-gradient(circle, #667eea 0%, transparent 70%);
  border-radius: 50%;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.table-info {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.table-title {
  flex: 1;
}

.table-type {
  margin: 0 0 5px 0;
  color: #303133;
  font-size: 22px;
  font-weight: 700;
  line-height: 1.2;
}

.table-name {
  margin: 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
  opacity: 0.8;
}

.table-details {
  flex: 1;
  margin-bottom: 20px;
}

.table-details p {
  margin: 8px 0;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-info {
  margin-bottom: 12px !important;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #e6a23c;
}

.description {
  font-size: 14px;
  color: #909399;
  line-height: 1.4;
}

.table-actions {
  text-align: center;
}

.cost-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cost-text {
  font-size: 18px;
  font-weight: bold;
  color: #e6a23c;
}

.cost-detail {
  font-size: 14px;
  color: #909399;
}

/* 时间段选择样式 */
.time-slots-container {
  width: 100%;
}

.time-slots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.time-slot-item {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.time-slot-item:hover:not(.disabled) {
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.time-slot-item.selected {
  border-color: #409eff;
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
}

.time-slot-item.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.time-slot-item.booked {
  border-color: #f56c6c;
  background: #fef0f0;
  color: #f56c6c;
}

.time-slot-item.past {
  border-color: #909399;
  background: #f5f7fa;
  color: #909399;
}

.slot-time {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.slot-status {
  font-size: 12px;
}

.status-text.available {
  color: #67c23a;
}

.status-text.selected {
  color: white;
}

.status-text.booked {
  color: #f56c6c;
}

.status-text.past {
  color: #909399;
}

.selected-summary {
  background: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 8px;
  padding: 16px;
  margin-top: 16px;
}

.selected-summary p {
  margin: 0 0 12px 0;
  color: #409eff;
  font-weight: 600;
}

.selected-slots {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .booking-container {
    padding: 15px;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    flex-direction: column;
    align-items: stretch;
    gap: 5px;
  }

  .tables-grid {
    grid-template-columns: 1fr;
  }

  .time-slots-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 8px;
  }

  .time-slot-item {
    padding: 8px;
  }
}
</style>
